#include <libdswutility/dswgpio.h>

#define GPIO_DEV "/dev/dswgpio_mixdvr"

CDswgpio::CDswgpio(LPST_ENV_T pEnv)
: CDswbase(pEnv)
, m_nGPIO_fd(-1)
, m_pBev(NULL)
, m_bRebooting(false)
{
	LOG4CPLUS_DEBUG(log_dsw, "Create CDswgpio class!");
	m_nGPIO_fd = open(GPIO_DEV, O_RDWR);
	if (m_nGPIO_fd < 0){
		LOG4CPLUS_WARN(log_dsw, "Can't open [ " << GPIO_DEV << " ], error = " << strerror(errno));
		return;
	}
//	m_pBev = bufferevent_socket_new(pEnv->pEvBase, m_nGPIO_fd, BEV_OPT_THREADSAFE);
//	bufferevent_setwatermark(m_pBev, EV_READ, sizeof(unsigned int), sizeof(unsigned int));
//	bufferevent_setcb(m_pBev, CDswgpio::cb_OnReadGPIO, NULL, NULL, this);
//	bufferevent_enable(m_pBev, EV_READ | EV_WRITE);
}

CDswgpio::~CDswgpio()
{
//	if (m_pBev)
//		bufferevent_free(m_pBev);
	if (m_nGPIO_fd != -1)
		close(m_nGPIO_fd);
	LOG4CPLUS_DEBUG(log_dsw, "Destroy CDswgpio class!");
}

void CDswgpio::OnReadGPIO(struct bufferevent *bev)
{
	struct evbuffer *input = bufferevent_get_input(bev);
	int nLen = (int)evbuffer_get_length(input);
	unsigned int nGPIOData;

	if (nLen >= sizeof(unsigned int)){
		bufferevent_read(bev, &nGPIOData, sizeof(unsigned int));
		if (nGPIOData & MASK_DEFAULT){
			if (!m_bRebooting){
				SendMessage(PMSG_SET_DEFAULT_PARAM, NULL);
				SendMessage(PMSG_SET_REBOOT, NULL);
				m_bRebooting = true;
			}
		}
	}
}

void CDswgpio::SetHDPower(bool bHDPowerOn)
{
	int nPowerOn;
	nPowerOn = bHDPowerOn ? 1 : 0;
	ioctl(m_nGPIO_fd, GPIO_SATA_PWR_CTL, &nPowerOn);
}

int CDswgpio::OnMessage(EN_MSG_TYPE nMsgType, void * pParam)
{
	switch(nMsgType){
	case PMSG_SET_HDPOWER:
		SetHDPower(*((bool*)pParam));
		break;
	}
	return 0;
}

